namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
    /// <summary>
    /// 1.  Start at Marketing homepage
    /// 2.	Open Campaign homepage
    /// 3.	Click on "New"
    /// 4.	Fill data and click "Save"
    /// 5.	Click on "Planning Tasks" on left pane
    /// 6.	Click on "New"
    /// 7.	Fill subject and description
    /// 8.  Click "Save and Close"
    /// 9.  Click "Save and Close"
    /// </summary>
    
    public class CreatePlanningTask : CrmWebTest
    {
        public void CreatePlanningTask_PreWebTest(object sender, PreWebTestEventArgs e)
        {
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable Props = new System.Collections.Hashtable();

            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }
                                    
            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];
            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];            
        }

        public void CreatePlanningTask_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            try
            {
                if (newCampaignId != null)
                {
                    Guid g = EntityManager.Instance.GetOwnerGuid(new Guid(user[EntityIDNames.User]), new Guid(user["OrganizationId"]));
                    EntityManager.Instance.AddEntity(EntityNames.Campaigns, g, new string[] { "OwningUser", "CampaignID", "EntityManagerOwningUser" }, new string[] { user["systemuserid"], newCampaignId.ToString(), g.ToString() });
                }
            }
            catch (System.FormatException fe)
            {
                System.Diagnostics.Trace.WriteLine("Failed to convert bogus data into Guid. " + fe.ToString());
            }
            finally
            {
                EntityManager.Instance.FreeEntity(user);
            }
        }

        private void CreatePlanningTask_ValidateResponse(object sender, ValidationEventArgs e)
        {
            string ID = null;

            int idIdx = e.Response.BodyString.IndexOf(newTaskIdMarker);
            ID = e.Response.BodyString.Substring(idIdx + (CreatePlanningTask.newTaskIdMarker.Length), 36);
            try
            {
                ID = new Guid(ID).ToString();
            }
            catch (System.FormatException fe)
            {
                System.Diagnostics.Trace.WriteLine("Format exception: " + fe.ToString());
                e.IsValid = false;
                return;
            }
            e.IsValid = true;
        }

        public CreatePlanningTask()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            refreshGridCampaign = GridXmlHelper.CampaignPageViewRefresh(-1, myCampaignViewId, null);

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(CreatePlanningTask_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(CreatePlanningTask_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            this.BeginTransaction("NavCampaignHomepage");

            MA_home_camps_aspx hp = new MA_home_camps_aspx(user);            
            yield return (hp);

            this.EndTransaction("NavCampaignHomepage");

            this.BeginTransaction("CreateCampaign");

            ma_camps_edit_aspx campPage = new ma_camps_edit_aspx(user);
            yield return (campPage);

            referer = campPage.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx f = new _forms_FormScript_js_aspx(user);
            f.etc = 4400;
            f.FormType = "main";
            f.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            f.Headers.Add(headerItem);
            yield return (f);

            _controls_number_formatNumber_xsl format = new _controls_number_formatNumber_xsl(crmServer);
            yield return (format);

            string campName = Utils.GetRandomString(5, 10);
            campPage = new ma_camps_edit_aspx(user);
            campPage.crmFormSubmitXml = EntityXmlHelper.GetCreateCampaignXml(new Guid(user[EntityIDNames.User]), 8); //campaign.Serialize();
            campPage.crmFormSubmitMode = 1;
            campPage.crmFormUserModified = true;
            campPage.crmFormSubmitObjectType = 4400;
            campPage.crmFormSubmitSecurity = 852023;
            campPage.crmFormSubmitOnline = 1;

            rpcInfo = Utils.GenerateWRPCToken(ma_camps_edit_aspx.url, user, tokenKey);
            campPage.CRMWRPCToken = rpcInfo.token;
            campPage.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            yield return (campPage);

            //get the newly created campaign id out of the post reply
            int idIdx = campPage.lastResponse.BodyString.IndexOf(newIdMarker);
            string tempNewCampaignId = campPage.lastResponse.BodyString.Substring(idIdx + (CreatePlanningTask.newIdMarker.Length), 36);
            newCampaignId = new Guid(tempNewCampaignId);

            AppGridWebService.AppGridWebService agws = new AppGridWebService.AppGridWebService();
            CrmRequest wtrRefresh = null;
            try { agws.Refresh(refreshGridCampaign); }
            catch (crmException x)
            {
                wtrRefresh = (CrmRequest)x.wtr;
                wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);

                string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtrRefresh.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtrRefresh.Headers.Add(headerItem);
                wtrRefresh.Method = "Post";
            }
            yield return (wtrRefresh);

            this.EndTransaction("CreateCampaign");

            this.BeginTransaction("OpenCampaign");

            ma_camps_edit_aspx openCamp = new ma_camps_edit_aspx(user);
            openCamp.id = newCampaignId;
            yield return (openCamp);

            referer = openCamp.lastResponse.ResponseUri.AbsoluteUri;

            f = new _forms_FormScript_js_aspx(user);
            f.etc = 4400;
            f.FormType = "main";
            f.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            f.Headers.Add(headerItem);
            yield return (f);
            
            this.EndTransaction("OpenCampaign");

            this.BeginTransaction("CreatePlanningTask");

            ma_camps_areas_aspx createCampaignAct = new ma_camps_areas_aspx(user);
            createCampaignAct.oId = newCampaignId;
            createCampaignAct.oType = 4400;
            createCampaignAct.security = 852023;
            createCampaignAct.tabSet = "areaTasks";
            yield return (createCampaignAct);

            activities_task_edit_aspx taskEdit = new activities_task_edit_aspx(user);
            taskEdit.pType = 4400;
            taskEdit.pId = newCampaignId;
            taskEdit.pName = campName;
            yield return (taskEdit);

            referer = taskEdit.lastResponse.ResponseUri.AbsoluteUri;

            f = new _forms_FormScript_js_aspx(user);
            f.etc = 4212;
            f.FormType = "main";
            f.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            f.Headers.Add(headerItem);
            yield return (f);

            taskEdit = new activities_task_edit_aspx(user);
            // QueryString parameters
            taskEdit.pType = 4400;
            taskEdit.pId = newCampaignId;
            taskEdit.pName = campName;

            //Form parameters
            taskEdit.crmFormSubmitXml = EntityXmlHelper.GetCreateTaskXml(new Guid(user[EntityIDNames.User]), 8, newCampaignId, 4400); //task.Serialize();
            taskEdit.crmFormSubmitMode = 1;
            taskEdit.crmFormUserModified = true;
            taskEdit.crmFormSubmitObjectType = 4212;
            taskEdit.crmFormSubmitSecurity = 852023;
            taskEdit.crmFormSubmitOnline = 1;

            rpcInfo = Utils.GenerateWRPCToken(activities_task_edit_aspx.url, user, tokenKey);
            taskEdit.CRMWRPCToken = rpcInfo.token;
            taskEdit.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            taskEdit.ValidateResponse += this.CreatePlanningTask_ValidateResponse;
            yield return (taskEdit);

            //get the newly created task id out of the post reply
            idIdx = taskEdit.lastResponse.BodyString.IndexOf(newTaskIdMarker);
            string tempNewPlanningTaskId = taskEdit.lastResponse.BodyString.Substring(idIdx + (CreatePlanningTask.newTaskIdMarker.Length), 36);
            newPlanningTaskId = new Guid(tempNewPlanningTaskId);
            
            // Make the CampaignActivity Grid for Campaign
            tempNewCampaignId = newCampaignId.ToString();
            listGrid = GridXmlHelper.TaskGridForCampaignViewRefresh(-1, TaskInCampaignViewId, null, tempNewCampaignId, "4400");
            agws = new AppGridWebService.AppGridWebService();
            wtrRefresh = null;
            try { agws.Refresh(listGrid); }
            catch (crmException x)
            {
                wtrRefresh = (CrmRequest)x.wtr;
                wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);

                string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtrRefresh.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtrRefresh.Headers.Add(headerItem);
                wtrRefresh.Method = "Post";
            }
            yield return (wtrRefresh);

            format = new _controls_number_formatNumber_xsl(crmServer);
            yield return (format);

            this.EndTransaction("CreatePlanningTask");
        }

        private const string newIdMarker = @"separator + ""id=";
        private const string newTaskIdMarker = @"separator + ""id=";
        private CRMEntity user;
        private Guid newCampaignId;
        private Guid newPlanningTaskId;
        private string refreshGridCampaign;
        private string listGrid;
        private string crmServer;
        private string tokenKey;
        private static string myCampaignViewId = "7F68A34B-26F1-430F-B3EF-7079F2925C69";
        private static string TaskInCampaignViewId = "2B5F5A5D-2D23-4FE7-AA58-E77995368AE7";

        private Guid orgId;
        private string referer;
        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
    }
}
